/*
 * @Descripttion : 图片管理器
 * @Author       : QianFox Team
 * @Date         : 2022-03-21 09:27:02
 * @LastEditors  : QianFox Team
 * @LastEditTime : 2024-08-08 15:52:27
 */

import { _typeOf } from './common/utils';
import { Manager } from './manager';
import {
    _verificationIsObject,
    _verificationUrl,
    _verificationCallback,
} from './common/verification';
import { observer } from './common/observer';
import { pagination } from './pagination';
import { message } from './message';
import { dialog } from './dialog';
import { loading, closeLoading } from './loading';
import { Confirmtip, confirmtip } from './confirmtip';

function ImagesManager() {
    Manager.call(this);
    // 常量
    this.className = 'images-manager';
    this.tabsId = 'imagesManagerTabs';
    this.title = '<strong>添加图片</strong><span>(选择所需图片)</span>';
    // class 类
    this.HANDLE = `.${this.className} .image-list .image`;
    this.CONTAINER = `.${this.className}`;
    this.HANDLE_TELETE = `.${this.className} .image-list .image i`;
    this.HANDLE_LOCAL_SEARCH = '.foxui-images-manager__local .search-input button.search';
    this.HANDLE_LOCAL_UPLOAD = '.foxui-images-manager__local .add-image-btn button';
    this.LOCAL_INPUT = '.foxui-images-manager__local .add-image-btn input';
    this.EXTRACT_INPUT = '.foxui-images-manager__extract-image .extract-input input';
    this.GROUP_LIST = '.foxui-images-manager__local .group-list';
    this.GROUP_ITEM = '.foxui-images-manager__local .group-list .group-item';
    this.GROUP_DELETE = '.foxui-images-manager__local .group-list .group-item .delete';
    this.GROUP_MODIFY = '.foxui-images-manager__local .group-list .group-item .modify';
    this.GROUP_ADD = '.foxui-images-manager__local .add-group button';
    this.LOCAL_RIGHT_PART = '.foxui-images-manager__local .right-part';
    // 数据
    this.groupList = []; // 分组列表：{ groupId: 2, title: '默认分组', type: 'system', count: 125, , state: false}, // type：1、all， 2、system， 3、custom
    this.localImgList = []; // 本地图片：[{ id: 2, url: 'http://cp.liuzhifang.com/images/idphoto/idphoto02.jpg', name: 'idphoto02.jpg' }]
    this.paginationOption = {
        type: 'solid',
        size: 'small',
        pageSize: 10,
        pageNum: 9,
        pageSizeList: [10, 20, 30, 50, 100],
        isShowJump: true,
        isShowTotal: true,
        isShowSize: true,
    };
    this.localPagination = {
        // total: 0,
        // currentPage: 1,
        // startDate: '',
        // endDate: '',
        // pageSize: 10,
    };
    this.choosedList = []; // 选中图片
    this.isStamped = 0; // 是否开启图文水印
    this.limitSize = ''; // 限制图片大小
}

Object.setPrototypeOf(ImagesManager.prototype, Manager.prototype);

ImagesManager.prototype._init = function () {
    this._bindMouseForImg();
    this._bindDeleteImg();
    this._addCustomer();
    this._bindSearch();
    this._bindUpload();
    this._bindUploadChange();
    this._bindGroupHandle();
    this._bindToggleStamped();
};

ImagesManager.prototype._contentHtml = function () {
    return [
        `<div class="foxui-tabs foxui-type-line" id="${this.tabsId}">`,
        '<div class="foxui-tabs-header">',
        '<div class="foxui-tabs-item is-active">本地图片</div>',
        '<div class="foxui-tabs-item">网络提取</div>',
        '<div style="position:absolute; right:20px; display:flex;">',
        '<div class="foxui-color-secondary foxui-mr-12">',
        '<i class="foxui-icon-wenti-o"></i>',
        `<span class="stamped-info">已${this.isStamped ? '开启' : '关闭'}图片水印</span>`,
        '</div>',
        `<div class="stamped-switch foxui-switch${this.isStamped ? ' is-checked' : ''}">`,
        `<input type="checkbox" class="foxui-switch-input" checked="${
            this.isStamped ? true : false
        }"/>`,
        '<span class="foxui-switch-core"></span>',
        '</div>',
        '</div>',
        '</div>',
        '<div class="foxui-tabs-content">',
        `<div class="foxui-tabs-pane">${this._localHtml()}</div>`,
        `<div class="foxui-tabs-pane">${this._extractHtml()}</div>`,
        '</div>',
        '</div>',
    ].join('');
};

ImagesManager.prototype._localHtml = function () {
    return [
        '<div class="foxui-images-manager__body foxui-images-manager__local">',
        '<div class="left-part">',
        `${this._leftPartHtml()}`,
        '</div>',
        '<div class="right-part">',
        `${this._rightPartHtml(this.localImgList)}`,
        '</div>',
        '</div>',
    ].join('');
};

ImagesManager.prototype._extractHtml = function () {
    return [
        '<div class="foxui-images-manager__extract-image">',
        '<div class="images-content">',
        '<div class="extract-input">',
        '<div class="foxui-input-group">',
        '<label>图片地址：</label>',
        `<input class="foxui-size-small" placeholder="请在此处粘贴图片地址" value="" />`,
        '</div>',
        `<p>需要http://......${
            this.limitSize ? '大小不要超过' + this.limitSize + 'M' : ''
        }，支持图片类型gif，jpg，png</p>`,
        '</div>',
        '</div>',
        '</div>',
    ].join('');
};

ImagesManager.prototype._leftPartHtml = function () {
    return [
        '<div class="add-group">',
        '<button class="foxui-size-small foxui-block">',
        '<i class="foxui-icon-jiahao-o"></i>',
        '<span>添加分组</span>',
        '</button>',
        '</div>',
        '<div class="group-list">',
        `${this._groupListHtml()}`,
        '</div>',
    ].join('');
};

ImagesManager.prototype._rightPartHtml = function (imgList) {
    return [
        '<div class="image-content">',
        // header
        '<div class="image-header">',
        '<div class="add-image-btn">',
        '<input type="file" accept="image/*" multiple style="display:none"/>',
        '<button class="foxui-size-small foxui-solid-primary">',
        '<i class="foxui-icon-jiahao-o"></i>',
        '<span>添加图片</span>',
        '</button>',
        `<span class="info">${
            this.limitSize || this.limitSize === 0 ? '大小不要超过' + this.limitSize + 'M' : ''
        }</span>`,
        '</div>',
        '<div class="search-input">',
        '<div class="foxui-picker foxui-date-picker search-start-date">',
        '<div class="foxui-picker-handle foxui-input-prefix">',
        `<input class="foxui-size-small" readonly="readonly" placeholder="请选择日期" value="${
            this.localPagination.startDate || ''
        }" />`,
        '<i class="foxui-icon-rili-o foxui-prefix-icon"></i>',
        '<i class="foxui-icon-cuowu-o foxui-suffix-icon foxui-suffix-clear"></i>',
        '</div>',
        '</div>',
        '<div class="horizontal-line"></div>',
        '<div class="foxui-picker foxui-date-picker search-end-date">',
        '<div class="foxui-picker-handle foxui-input-prefix">',
        `<input class="foxui-size-small" readonly="readonly" placeholder="请选择日期" value="${
            this.localPagination.endDate || ''
        }" />`,
        '<i class="foxui-icon-rili-o foxui-prefix-icon"></i>',
        '<i class="foxui-icon-cuowu-o foxui-suffix-icon foxui-suffix-clear"></i>',
        '</div>',
        '</div>',
        '<button class="foxui-size-small foxui-solid-primary search">搜索</button>',
        '</div>',
        '</div>',
        // list
        '<div class="image-list">',
        '<div class="foxui-row foxui-gutter-4">',
        `${this._imageListHtml(imgList)}`,
        '</div>',
        '</div>',
        // footer
        '<div class="image-footer">',
        `<di class="local-pagination"></di>`,
        '</div>',
        '</div>',
    ].join('');
};

ImagesManager.prototype._groupListHtml = function () {
    // 分组列表
    let groupHtmlArr = [];
    this.groupList.forEach(item => {
        let itemHtml = [
            `<li class="group-item ${item.type} ${item.state ? 'is-active' : ''}" data-id="${
                item.groupId
            }">`,
            `<div class="title">${item.title || ''}</div>`,
            `<div class="count">${item.count || ''}</div>`,
            `${
                item.type === 'custom'
                    ? '<div class="modify-btn"><span class="modify">编辑</span><b>|</b><span class="delete">删除</span></div>'
                    : ''
            }`,
            '</li>',
        ].join('');
        groupHtmlArr.push(itemHtml);
    });
    return groupHtmlArr.join('');
};

ImagesManager.prototype._imageListHtml = function (imgList) {
    // 图片列表
    let imgListHtmlArr = [];
    imgList.forEach(item => {
        imgListHtmlArr.push(
            [
                `<div class="column-5">`,
                `<div class="image" data-imgid="${item.id}">`,
                `<img data-id="${item.id}" src="${item.url}"/>`,
                '<i class="foxui-icon-cuowu-f"></i>',
                `<span class="size">${item.size || '暂无尺寸'}</span>`,
                '</div>',
                '<div class="text">',
                `<span>${item.name}</span>`,
                '</div>',
                '</div>',
            ].join('')
        );
    });
    return imgListHtmlArr.join('');
};

/**
 * @description: 添加分页
 * @param {*} type
 * @return {*}
 * @Date: 2022-04-18 20:20:01
 */
ImagesManager.prototype._addPagination = function (type) {
    let that = this,
        localPaginationOption = JSON.parse(JSON.stringify(this.paginationOption));

    // 设置本地页码
    const { pageSize: localPageSize, pageSizeList: localPageSizeList } = this.localPagination;
    localPageSize && (localPaginationOption.pageSize = localPageSize);
    localPageSizeList && (localPaginationOption.pageSizeList = localPageSizeList);

    // 本地图片
    if (!type || type === 'local') {
        pagination(
            {
                el: `.${this.className} .local-pagination`,
                currentPage: this.localPagination.currentPage,
                total: this.localPagination.total,
                onchange: function ({ currentPage, pageSize }) {
                    loading({
                        el: `.${that.className}`,
                        text: '图片加载中...',
                    });
                    that.localPagination.currentPage = currentPage;
                    that.localPagination.pageSize = pageSize;
                    that._ajax(
                        that._uploadData({
                            handle: 'get',
                        })
                    );
                },
            },
            localPaginationOption
        );
    }
};

/**
 * @description: 绑定鼠标事件(鼠标移入、鼠标移出、鼠标点击->选中)
 * @param {*}
 * @return {*}
 * @Date: 2022-04-17 20:36:54
 */
ImagesManager.prototype._bindMouseForImg = function () {
    let that = this;
    $(document).on('mouseover', this.HANDLE, function () {
        let $this = $(this),
            isActive = $this.is('.is-active');
        if (!isActive) {
            $this.find('i, .size').fadeIn(100);
        }
    });

    $(document).on('mouseleave', this.HANDLE, function () {
        let $this = $(this),
            isActive = $this.is('.is-active');
        if (!isActive) {
            $this.find('i, .size').fadeOut(100);
        }
    });

    $(document).on('click', this.HANDLE, function () {
        let choosedList = [],
            $this = $(this),
            $container = $this.closest(that.CONTAINER),
            isActive = $this.is('.is-active');
        if (isActive) {
            $this.removeClass('is-active');
            $this.find('i, .size').fadeIn(100);

            // 保存选中的图片 (保存选中的图片有先后顺序) -> 删除
            let imgId = $this.find('img').attr('data-id'),
                imgUrl = $this.find('img').attr('src');
            if (imgId) {
                that.choosedList = that.choosedList.filter(item => item.id !== imgId);
            } else {
                that.choosedList = that.choosedList.filter(item => item.url !== imgUrl);
            }
        } else {
            $this.addClass('is-active');
            $this.find('i, .size').fadeOut(100);

            // 保存选中的图片 保存选中的图片 (保存选中的图片有先后顺序) -> 添加
            that.choosedList.push({
                id: $this.find('img').attr('data-id'),
                url: $this.find('img').attr('src'),
            });
        }
        
        // 保存选中的图片
        // $container.find('.image-list .image.is-active').each(function () {
        //     const $img = $(this).find('img'),
        //         id = $img.attr('data-id'),
        //         url = $img.attr('src');
        //     choosedList.push({ id, url });
        // });
        // that.choosedList = choosedList;
    });
};

/**
 * @description: 绑定删除图片
 * @param {*}
 * @return {*}
 * @Date: 2022-04-18 20:36:58
 */
ImagesManager.prototype._bindDeleteImg = function () {
    let that = this;
    $(document).on('click', this.HANDLE_TELETE, function (event) {
        let handle = this;
        event.stopPropagation();
        dialog({
            title: '删除',
            content: '您确定要删除图片吗',
            cancelText: '取消',
            confirmText: '删除',
            buttonType: 'danger',
            confirm: function (callback) {
                // 收集数据
                let $img = $(handle).siblings('img'),
                    deleteId = $img.attr('data-id');
                // 关闭对话框
                callback();
                loading({
                    el: `.${that.className}`,
                    text: '图片正在删除中...',
                });
                // 请求
                that._ajax(
                    that._uploadData({
                        handle: 'deleteImage',
                        deleteId,
                    })
                );
                // 删除成功提示
                message({
                    text: '图片删除成功',
                    type: 'success',
                });
            },
        });
    });
};

/**
 * @description: 绑定按日期搜索
 * @param {*}
 * @return {*}
 * @Date: 2022-04-18 22:58:16
 */
ImagesManager.prototype._bindSearch = function () {
    let that = this;
    $(document).on('click', this.HANDLE_LOCAL_SEARCH, function () {
        that.localPagination.currentPage = 1;
        that._search(this);
    });
};

/**
 * @description: 按日期搜索
 * @param {*} handle
 * @return {*}
 * @Date: 2022-04-18 22:50:05
 */
ImagesManager.prototype._search = function (handle) {
    // 数据收集
    let startDate = $(handle).siblings('.search-start-date').find('input').val(),
        endDate = $(handle).siblings('.search-end-date').find('input').val();
    // 添加加载层
    loading({
        el: `.${this.className}`,
        text: '图片加载中...',
    });
    // 获取数据
    this._ajax(
        this._uploadData({
            handle: 'get',
            startDate,
            endDate,
        })
    );
};

/**
 * @description: 绑定上传图片
 * @param {*}
 * @return {*}
 * @Date: 2022-04-18 23:22:09
 */
ImagesManager.prototype._bindUpload = function () {
    $(document).on('click', this.HANDLE_LOCAL_UPLOAD, function () {
        let $input = $(this).siblings('input[type="file"]');
        $input.val('');
        $input[0].click();
    });
};

/**
 * @description: 绑定上传文件改变时
 * @param {*}
 * @return {*}
 * @Date: 2022-04-18 23:44:18
 */
ImagesManager.prototype._bindUploadChange = function () {
    let that = this;
    $(document).on('change', this.LOCAL_INPUT, function (event) {
        // 添加进度条
        that._addProgress('图片');

        let files = event.target.files,
            len = files.length;

        for (let i = 0; i < len; i++) {
            let file = files[i];

            if (file.type.split('/')[0] !== 'image') {
                // 关闭进度条
                if (that.progress) that._removeProgress();
                message({
                    text: `上传文件${file.name}不是图片`,
                    type: 'danger',
                });
                return false;
            }

            if (file.size > that.limitSize * 1024 * 1024) {
                // 关闭进度条
                if (that.progress) that._removeProgress();
                message({
                    text: `上传图片${file.name}不能大于${that.limitSize}M`,
                    type: 'danger',
                });
                return false;
            }
        }

        that._upload(files);
    });
};

/**
 * @description: 上传文件
 * @param {*} files
 * @return {*}
 * @Date: 2022-04-18 23:45:06
 */
ImagesManager.prototype._upload = function (files) {
    // 请求
    this._ajax(
        this._uploadData({
            handle: 'upload',
            files,
            isStamped: this.isStamped,
        })
    );
};

/**
 * @description: 转图片转为二进制（暂时没用，直接上传 file）
 * @param {*} img
 * @return {*}
 * @Date: 2022-04-25 09:09:26
 */
ImagesManager.prototype._imageToBase64 = function (img) {
    return new Promise(resolve => {
        let reader = new FileReader();
        //转化二进制流，异步方法
        reader.readAsDataURL(img);
        reader.onload = e => {
            resolve(e.target.result);
        };
    });
};

/**
 * @description: 绑定组的相关操作
 * @param {*}
 * @return {*}
 * @Date: 2022-04-19 10:30:00
 */
ImagesManager.prototype._bindGroupHandle = function () {
    let that = this;
    $(document).on('click', this.GROUP_ITEM, function () {
        let $this = $(this),
            $items = $this.siblings('.group-item'),
            isActive = $this.is('.is-active');
        if (!isActive) {
            // 切换组
            $($items).filter('.is-active').removeClass('is-active');
            $(this).addClass('is-active');
            // 重置页码
            that.localPagination.currentPage = 1;
            // 摸拟接收数据
            loading({
                el: `.${that.className}`,
                text: '图片加载中...',
            });
            // 请求
            that._ajax(
                that._uploadData({
                    handle: 'get',
                })
            );
        }
    });

    $(document).on('click', this.GROUP_DELETE, function (event) {
        event.stopPropagation();
        let handle = this;
        dialog({
            title: '删除',
            content: '您确定要删除图片组吗',
            cancelText: '取消',
            confirmText: '删除',
            buttonType: 'danger',
            confirm: function (callback) {
                // 收集数据
                let groupId = $(handle).closest('.group-item').attr('data-id');
                // 关闭对话框
                callback();
                loading({
                    el: `.${that.className}`,
                    text: '图片组正在删除中...',
                });
                // 请求
                that._ajax(
                    that._uploadData({
                        handle: 'deleteGroup',
                        groupId,
                    })
                );
                message({
                    text: '图片组删除成功',
                    type: 'success',
                });
            },
        });
    });
};

/**
 * @description: 添加组
 * @return {*}
 * @Date: 2022-08-19 09:13:41
 */
ImagesManager.prototype._addGroupInit = function () {
    let that = this;
    confirmtip({
        el: that.GROUP_ADD,
        title: '添加标题',
        content: `<input class="foxui-size-small"/>`,
        width: '220px',
        isRemove: true,
        cancelText: '取消',
        confirmText: '添加',
        confirm: function () {
            const btnFoxId = $(that.GROUP_ADD).attr('data-foxid'),
                $confirmtip = $(`#${btnFoxId}`),
                groupName = $confirmtip.find('input').val();

            if (groupName) {
                loading({
                    el: `.${that.className}`,
                    text: '正在添加组...',
                });
                that._ajax(
                    that._uploadData({
                        handle: 'addGroup',
                        groupName,
                    })
                );
            } else {
                message({
                    text: '请输入标题',
                    type: 'danger',
                });
            }
        },
    });
};

/**
 * @description: 修改组
 * @return {*}
 * @Date: 2022-08-19 10:14:48
 */
ImagesManager.prototype._modifyGroupInit = function () {
    let that = this;

    $(this.GROUP_MODIFY).each(function () {
        const $this = $(this),
            hasFoxid = $this.attr('data-foxid') ? true : false;

        if (!hasFoxid) {
            let confirmtip = new Confirmtip(),
                foxid = confirmtip.foxId,
                title = $this.closest('.custom').find('.title').text();

            $(this).attr('data-foxid', foxid);

            confirmtip._init({
                el: `${that.GROUP_MODIFY}[data-foxid=${foxid}]`,
                title: '修改标题',
                content: `<input class="foxui-size-small" value="${title}"/>`,
                width: '220px',
                isRemove: true,
                cancelText: '取消',
                confirmText: '修改',
                confirm: function () {
                    const $confirmtip = $(`#${foxid}`),
                        groupId = $this.closest('.custom').attr('data-id'),
                        groupName = $confirmtip.find('input').val();

                    if (groupName) {
                        loading({
                            el: `.${that.className}`,
                            text: '正在修改组...',
                        });
                        that._ajax(
                            that._uploadData({
                                handle: 'modifyGroup',
                                groupName,
                                groupId,
                            })
                        );
                    } else {
                        message({
                            text: '请输入标题',
                            type: 'danger',
                        });
                    }
                },
            });
        }
    });
};

/**
 * @description: 转换 type：0、local(本地图片)；1、extract(提取图片)
 * @param {*} index
 * @return {*}
 * @Date: 2022-04-18 21:18:08
 */
ImagesManager.prototype._changeType = function (index) {
    switch (index) {
        case 0:
            return 'local';
        case 1:
            return 'extract';
        default:
            return '';
    }
};

/**
 * @description: 绑定切换开启/关闭给图片加水印
 * @return {*}
 * @Date: 2023-06-05 13:38:42
 */
ImagesManager.prototype._bindToggleStamped = function () {
    let that = this;

    $(document).on('click', `#${this.tabsId} .stamped-switch`, function () {
        // 调整数据
        that._toggleStamped(this);
        // 添加加载层
        loading({
            el: `.${that.className}`,
            text: '加载中...',
        });
        // 请求数据
        that._ajax({ isStamped: that.isStamped }, 'stamped');
    });
};

/**
 * @description: 切换开启/关闭给图片加水印
 * @param {*} el                         水印开关节点
 * @return {*}
 * @Date: 2023-06-05 15:27:28
 */
ImagesManager.prototype._toggleStamped = function (el) {
    let $stampedInfo = $(el).closest('.foxui-tabs').find('.stamped-info'),
        isChecked = $(el).is('.is-checked');

    // 修改需要上传的数据
    this.isStamped = isChecked ? 1 : 0;
    // 修改图片水印节点信息
    if (isChecked) {
        $stampedInfo.text('已开启图片水印');
    } else {
        $stampedInfo.text('已关闭图片水印');
    }
};

ImagesManager.prototype._uploadData = function ({
    handle,
    deleteId,
    files,
    groupId,
    groupName,
    startDate,
    endDate,
    extractUrl,
    isStamped,
}) {
    let type = this._changeType(this.tabsIndex),
        uploadData = {
            handle,
            type,
        };

    if (type === 'local') {
        let currentPage = this.localPagination.currentPage,
            pageSize = this.localPagination.pageSize;
        groupId = groupId || $(this.GROUP_ITEM).filter('.is-active').attr('data-id');

        if (handle === 'get') {
            uploadData.currentPage = currentPage;
            uploadData.pageSize = pageSize;
            uploadData.groupId = groupId;
            uploadData.startDate = startDate;
            uploadData.endDate = endDate;
        } else if (handle === 'upload') {
            let formData = new FormData();
            for (let key in files) {
                formData.append('file[]', files[key]);
            }
            formData.append('pageSize', pageSize);
            formData.append('groupId', groupId);
            formData.append('event', 'change');
            formData.append('handle', 'upload');
            formData.append('type', type);
            formData.append('isStamped', isStamped);
            uploadData.formData = formData;
        } else if (handle === 'deleteImage') {
            uploadData.pageSize = pageSize;
            uploadData.groupId = groupId;
            uploadData.id = deleteId;
        } else if (handle === 'addGroup') {
            uploadData.groupName = groupName;
        } else if (handle === 'deleteGroup') {
            uploadData.groupId = groupId;
            uploadData.groupName = groupName;
        } else if (handle === 'modifyGroup') {
            uploadData.groupId = groupId;
            uploadData.groupName = groupName;
        }
    } else {
        uploadData.extractUrl = extractUrl;
        uploadData.isStamped = isStamped;
    }
    return uploadData;
};

/**
 * @description: 点击确定后，执行函数
 * @param {*} callback
 * @return {*}
 * @Date: 2022-04-18 21:20:01
 */
ImagesManager.prototype._confirm = function (callback) {
    // 判断是选择图片，还是网络提取
    if (this.tabsIndex < 1) {
        // 判断是否已选择图片
        if (this.choosedList.length > 0) {
            // 发布消息(内部)
            observer._publiced('imagesManager', {
                choosedList: this.choosedList,
                target: this.target,
            });
            // 发布消息
            let subid = $(this.target).closest('[data-subid]').attr('data-subid');
            if (subid) observer._publiced('custom', this.choosedList, subid, 'confirm');
            // 修复第二次打开时，数据还存在
            this.choosedList = [];
            // 关闭对话框
            callback();
        } else {
            message({
                text: '请先选择图片',
                type: 'danger',
            });
        }
    } else {
        let extractUrl = $(this.EXTRACT_INPUT).val();
        if (_verificationUrl(extractUrl)) {
            loading({
                el: `.${this.className}`,
                text: '图片提取中...',
            });
            // 获取数据;
            this._ajax(
                this._uploadData({
                    handle: 'get',
                    extractUrl,
                    isStamped: this.isStamped,
                })
            );
            // 关闭对话框
            callback();
        } else {
            message({
                text: '请输入正确的图片地址',
                type: 'danger',
            });
        }
    }
};

/**
 * @description: 更新节点 (非初始化时)
 * @param {*} data
 * @return {*}
 * @Date: 2022-04-24 10:09:56
 */
ImagesManager.prototype._update = function (data) {
    let $groupList = $(this.GROUP_LIST),
        $localRightPart = $(this.LOCAL_RIGHT_PART);
    const {
        type,
        currentPage,
        total,
        pageSize,
        startDate,
        endDate,
        groupList,
        imgList,
        isStamped,
    } = data;

    if (type === 'local') {
        this.groupList = groupList;
        this.localPagination.total = total;
        this.localPagination.currentPage = currentPage;
        this.localPagination.startDate = startDate;
        this.localPagination.endDate = endDate;
        this.localPagination.pageSize = pageSize;
        this.isStamped = parseInt(isStamped) === 1 ? 1 : 0;
        $groupList.empty().append(this._groupListHtml());
        $localRightPart.empty().append(this._rightPartHtml(imgList));
        this._addPagination(type);
    } else {
        const { id, extractedUrl } = data;
        // 发布消息(内部)
        observer._publiced('imagesManager', {
            choosedList: [{ id, url: extractedUrl }],
            target: this.target,
        });
        // 发布消息
        let subid = $(this.target).closest('[data-subid]').attr('data-subid');
        if (subid) observer._publiced('custom', [{ id, url: extractedUrl }], subid, 'confirm');
    }
};

/**
 * @description: 获取数据  data:{ handle, type, currentPage, pageSize, startDate, endDate, groupId, id, url, files }
 * @param {*} event                处理事件：1、初始化：init，  2、改变时：change， 3、水印开关：stamped
 * @param {*} handle               处理方式：1、get， 2、upload，3、deleteImage， 4、addGroup， 5、deleteGroup，6、modifyGroup
 * @param {*} type                 类型：01、local， 1、extract
 * @param {*} currentPage          当前页
 * @param {*} pageSize             每页显示多少条
 * @param {*} startDate            开始日期
 * @param {*} endDate              结束日期
 * @param {*} groupId              组id
 * @param {*} id                   图片id
 * @param {*} url                  提取图片地址
 * @param {*} files                上传文件
 * @param {*} isStamped            是否打开图片水印：1、打开， 2、关闭
 * @return {*}
 * @Date: 2022-04-24 09:23:14
 */
ImagesManager.prototype._ajax = function (data, event) {
    let that = this,
        params = {
            type: 'post',
            url: this.url,
            async: event === 'init' ? false : true,
            xhr: function () {
                let xhr = new XMLHttpRequest();
                xhr.upload.addEventListener(
                    'progress',
                    function (event) {
                        if (event.lengthComputable) {
                            let percentComplete = (event.loaded / event.total) * 100;
                            if (that.progress) {
                                that.progress.update(parseInt(percentComplete));
                            }
                        }
                    },
                    false
                );
                return xhr;
            },
            success: function (res) {
                // 判断是不是初始化，切换开启/关闭图片水印
                if (event === 'init') {
                    if (res.code === 1) {
                        const { groupList, localImgList, localPagination, isStamped, limitSize } =
                            res.data;
                        that.groupList = groupList;
                        that.localImgList = localImgList;
                        that.localPagination = localPagination;
                        that.isStamped = parseInt(isStamped) === 1 ? 1 : 0;
                        parseFloat(limitSize) && (that.limitSize = parseFloat(limitSize));
                    } else {
                        message({
                            text: res.msg,
                            type: 'danger',
                        });
                    }
                    // 关闭加载层
                    closeLoading();
                } else if (event === 'stamped') {
                    // 如不是初始化，更新
                    if (res.code !== 1) {
                        message({
                            text: res.msg,
                            type: 'danger',
                        });

                        // 请求失败，回退图片水印开关状态
                        let $stampedSwitch = $(`#${this.tabsId} .stamped-switch`),
                            isChecked = $stampedSwitch.is('.is-checked');

                        if (isChecked) {
                            $stampedSwitch.removeClass('is-checked');
                        } else {
                            $stampedSwitch.addClass('is-checked');
                        }

                        that._toggleStamped($stampedSwitch);
                    }
                    // 关闭加载层
                    closeLoading(`.${that.className}`);
                } else {
                    // 如不是初始化，更新
                    if (res.code === 1) {
                        that._update(res.data);
                        // 初始化 修改组
                        that._modifyGroupInit && that._modifyGroupInit();
                    } else {
                        message({
                            text: res.msg,
                            type: 'danger',
                        });
                    }
                    // 关闭加载层
                    closeLoading(`.${that.className}`);
                    // 关闭进度条
                    if (that.progress) that._removeProgress();
                }
            },
            error: function (xhr, status, error) {
                // 关闭加载层
                closeLoading(`.${that.className}`);
                // 关闭进度条
                if (that.progress) that._removeProgress();
                message({
                    text: '图片上传失败',
                    type: 'danger',
                });
            },
        };
    // 判断是不是上传文件
    if (data.handle === 'upload') {
        params.data = data.formData;
        params.contentType = false;
        params.processData = false;
        // 前面已追加了 event 到 formData
    } else {
        // 添加 event
        data.event = event || 'change';
        params.data = data;
    }
    // 添加加载层
    if (event === 'init') loading();
    // 发起请求
    $.ajax(params);
};

/**
 * @description: 添加订阅者(内部) --> 确认时
 * @param {*} callback
 * @return {*}
 * @Date: 2022-04-18 17:19:12
 */
ImagesManager.prototype._onConfirm = function (callback) {
    observer._subscribe('imagesManager', callback);
};

/**
 * @description: 添加订阅者 --> 确认时
 * @param {*} subid
 * @param {*} callback
 * @return {*}
 * @Date: 2024-08-06 10:21:40
 */
ImagesManager.prototype.onConfirm = function (subid, callback) {
    if (subid && _typeOf(callback) === 'function') {
        observer._subscribe('custom', callback, subid, 'confirm');
    }
};

/**
 * @description: 取消订阅(内部) --> 确认时
 * @param {*} callback
 * @return {*}
 * @Date: 2022-04-18 17:19:52
 */
ImagesManager.prototype._unConfirm = function (callback) {
    observer._unsubscribe('imagesManager', callback);
};

/**
 * @description: 取消订阅 --> 确认时
 * @param {*} subid
 * @return {*}
 * @Date: 2024-08-06 10:22:07
 */
ImagesManager.prototype.unConfirm = function (subid) {
    if (subid) observer._unsubscribe('custom', null, subid, 'confirm');
};

/**
 * @description: 初始化设置
 * @param {*} paginationOption       分页配置
 * @param {*} url                    图片接口地址
 * @return {*}
 * @Date: 2022-04-24 10:15:31
 */
ImagesManager.prototype.init = function ({ paginationOption, url }) {
    // 校验 paginationOption
    paginationOption && _verificationIsObject(paginationOption, true, 'paginationOption');
    // 保存
    paginationOption && (this.paginationOption = paginationOption);
    this.url = url;
};

let imagesManager = new ImagesManager();

export { imagesManager };